<template>
  <div class="adminnew">
    <div class="adminmsg">
      <div class="top">
        <h2>消息管理</h2>
        <el-button class="btnhouse" size="small" @click="dialogForm = true">
          <i class="el-icon-plus"></i>  发布消息
        </el-button>
      </div>
      <div class="title block">
        <span>标题</span>
        <span>时间</span>
        <span>操作</span>
      </div>
      <div v-for="item in list" :key="item.id">
        <div class="info block">
          <div class="msg">
            <p>{{ item.title }}</p>
            <p>{{ item.content }}</p>
          </div>
          <div class="msg">
            <p>{{ item.create_time }}</p>
          </div>
          <div>
            <el-button type="primary" size="small" @click="edit(item)">编辑</el-button>
            <el-button type="danger" size="small" @click="remoke(item.id)">删除</el-button>
          </div>
        </div>
      </div>
      <div class="Page">
        <el-pagination @current-change="handlePage" :current-page.sync="currentPage" layout="prev, pager, next"
          :total="allList.length" :page-size="5">
        </el-pagination>
      </div>
      <!-- 发布消息资讯弹窗 -->
      <el-dialog title="发布消息资讯" :visible.sync="dialogForm" :before-close="handleClose" width="35%">
        <el-form :model="form" :rules="rules" ref="newsForm">
          <el-form-item label="标题" :label-width="'80px'" prop="title">
            <el-input v-model="form.title"></el-input>
          </el-form-item>
          <el-form-item label="内容" :label-width="'80px'" prop="content">
            <el-input type="textarea" :rows="3" placeholder="请输入内容" v-model="form.content">
            </el-input>
          </el-form-item>
          <el-form-item label="房源选择" :label-width="'80px'" prop="houseid">
            <el-select v-model="form.houseid" placeholder="请选择房源" style="width: 100%;">
              <el-option v-for="(item, index) in houses" :key="item.value" :label="item.label" :value="item.value"
                class="formOption">
                <span style="width: 20px;">{{ index + 1 }}</span>
                <img :src="item.image" alt="" class="formImage">
                <span style="overflow: hidden;">{{ item.label }}</span>
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="handleClose">取 消</el-button>
          <el-button type="primary" @click="newsPush">发 布</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import dateTime from '@/utils/TimeFormat'
export default {
  name: 'adminnews',
  mixins: [dateTime],
  created() {
    this.getNewsList()
    this.getHouseList()
  },
  data() {
    return {
      //当前页
      currentPage: 1,
      //发布消息资讯弹窗
      dialogForm: false,
      form: {
        title: '',
        content: '',
        houseid: ''
      },
      //消息列表
      allList: [],
      list: [],
      houses: [],
      rules: {
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入内容', trigger: 'blur' },
          { min: 2, max: 200, message: '长度在 2 到 200 个字符', trigger: 'blur' }
        ],
        houseid: [
          { required: true, message: '请选择房源', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    //分页
    handlePage(page) {
      const start = (page - 1) * 5
      const end = page * 5
      this.list = this.allList.slice(start, end)
    },
    //获取新闻列表
    async getNewsList(page = 1) {
      const { data: res } = await this.$axios.get('/api/news/list')
      if (res.status == '200') {
        this.allList = this.formatList(res.data)
        this.list = this.allList.slice(0, 5)
      }
      //之后再获取数据后不会跳回第一页而是保持在当前页
      this.handlePage(page)
    },
    //获取房源列表，用于发布消息
    async getHouseList() {
      const { data: res } = await this.$axios.get('/api/house/unrented')
      if (res.status == '200') {
        this.houses = res.data.map(item => {
          return {
            value: item.id,
            label: item.title,
            image: item.img_url[0],
          }
        })
      }
    },
    //发布消息
    async newsPush() {
      //判断是新增还是修改,新增则没有id
      if (this.form.id == undefined) {
        this.$refs['newsForm'].validate(async (valid) => {
          if (valid) {
            const { data: res } = await this.$axios.post('/api/news/add', this.form)
            if (res.status == '200') {
              this.$message({
                message: '发布成功',
                type: 'success'
              })
            }
            this.handleClose()
            this.getNewsList(this.currentPage)
          }
        });
      } else {
        this.$refs['newsForm'].validate(async (valid) => {
          if (valid) {
            const { data: res } = await this.$axios.post('/api/news/edit', {
              id: this.form.id,
              title: this.form.title,
              content: this.form.content,
              houseid: this.form.houseid
            })
            if (res.status == '200') {
              this.$message({
                message: '修改成功',
                type: 'success'
              })
            }
            this.handleClose()
            this.getNewsList(this.currentPage)
          }
        });
      }
    },
    //删除消息
    async remoke(id) {
      const { data: res } = await this.$axios.get(`/api/news/delete/${id}`)
      if (res.status == '200') {
        this.$message({
          message: '删除成功',
          type: 'success'
        })
        this.getNewsList(this.currentPage)
      }
    },
    //编辑消息
    edit(val) {
      this.form = {
        title: val.title,
        content: val.content,
        id: val.id,
        houseid: val.houseid
      }
      this.dialogForm = true
    },
    //点击取消或遮罩层关闭弹窗
    handleClose() {
      this.$refs['newsForm'].resetFields();
      this.form = {
        title: '',
        content: '',
        houseid: ''
      },
      this.dialogForm = false
    }
  }
}
</script>

<style scoped>
.adminnew {
    width: 100%;
    min-height: calc(100vh - 60px);
    background-color: #f5f7fa;
    padding: 30px;
    box-sizing: border-box;
}

.adminmsg {
    width: 100%;
    background-color: #fff;
    border-radius: 12px;
    padding: 30px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.top {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 1px solid #ebeef5;
}

.top h2 {
    font-size: 22px;
    font-weight: 600;
    color: #303133;
    margin: 0;
}

.btnhouse {
    background-color: #4a5eff;
    border: none;
    color: white;
    border-radius: 6px;
    padding: 10px 20px;
    transition: all 0.3s;
}

.btnhouse:hover {
    background-color: #3a4de8;
    box-shadow: 0 2px 12px rgba(74, 94, 255, 0.2);
    transform: translateY(-2px);
}

.Page {
    display: flex;
    justify-content: center;
    margin-top: 40px;
    padding-top: 20px;
    border-top: 1px solid #ebeef5;
}

.block {
    display: flex;
    align-items: center;
    width: 100%;
    flex-wrap: wrap;
    gap: 20px;
}

.block > :first-child {
    flex: 3;
    min-width: 250px;
}

.block > :nth-child(n+2) {
    flex: 1;
    min-width: 120px;
}

.title {
    height: 50px;
    background-color: #4b5fff;
    color: white;
    padding: 0 20px;
    margin: 25px 0 15px;
    border-radius: 8px;
    font-weight: 500;
    display: flex;
    align-items: center;
}

.title span {
    flex: 1;
}

.info {
    padding: 25px 0;
    border-bottom: 1px solid #ebeef5;
    display: flex;
    flex-wrap: wrap;
    gap: 20px;
    transition: all 0.3s ease;
}

.info:hover {
    background-color: #fafafa;
}

.info .msg {
    color: #606266;
    line-height: 1.6;
}

.formOption {
    display: flex;
    align-items: center;
    height: 100px;
    padding: 0 10px;
    transition: all 0.3s;
}

.formOption:hover {
    background-color: #fafafa;
}

.formImage {
    width: 100px;
    height: 80px;
    margin-right: 10px;
    margin-left: 5px;
    object-fit: cover;
    border-radius: 4px;
}

.el-button {
    transition: all 0.3s;
}

.el-button:hover {
    transform: translateY(-2px);
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.el-dialog {
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.el-dialog__title {
    font-size: 18px;
    font-weight: 600;
    color: #303133;
}

.el-dialog__footer {
    border-top: 1px solid #ebeef5;
    padding: 15px 20px;
    display: flex;
    justify-content: flex-end;
}

@media (max-width: 768px) {
    .adminnew {
        padding: 15px;
    }

    .adminmsg {
        padding: 20px;
    }
}
</style>    